import { Directive, ElementRef, Input, OnInit, OnDestroy } from '@angular/core';
//Controls
import { AmChartsService } from "@amcharts/amcharts3-angular";

import * as _ from 'lodash';

@Directive({
    selector: '[ratingDistributionChart]'
})
export class DistributionChartDirective implements OnInit, OnDestroy {
    private chart: any;
    private _chartData: any[];
    private arrowSet: boolean = false;
    private maxRating: number;

    @Input() chartID: string;
    @Input() riskLevels: any[]; //list of company subIndustry clusters
    @Input() companyName: string;
    @Input() companyRiskLevel: any; //cluster code
    @Input() showRiskLevels: boolean;
    @Input() hidePlus: boolean;
    @Input() primaryName: string;
    @Input() secondaryName: string;
    @Input() set chartData(value: any[]) {
        if (value) {
            this._chartData = value;
            if (this.chart) {
                this.AmCharts.updateChart(this.chart, () => {
                    this.maxRating = this.getMaxRating();
                    this.chart.dataProvider = this._chartData;
                    this.chart.graphs = this.setGraphs();
                });
            }
        }
    }

    constructor(private el: ElementRef, private AmCharts: AmChartsService) { }

    ngOnInit() {
        this.maxRating = this.getMaxRating();

        //generate chart without data. data will be added when getting the chartData
        this.chart = this.AmCharts.makeChart(this.chartID, {
            type: "serial",
            gridCount: 10,
            autoMargins: false,
            marginTop: 15,
            marginBottom: 2,
            marginLeft: 0,
            marginRight: 0,
            dataProvider: this._chartData,
            valueAxes: [{
                axisAlpha: 0,
                labelsEnabled: false,
                unit: '%',
                dashLength: 0,
                gridAlpha: 0,
                minVerticalGap: 40,
                minimum: 0,
                maximum: this.maxRating
            }],
            gridAboveGraphs: false,
            columnSpacing: 5,
            startDuration: 0, //animation disabled because of angular2-ie9-shims making it slow
            graphs: this.setGraphs(),
            chartCursor: {
                oneBalloonOnly: true,
                categoryBalloonEnabled: false,
                cursorAlpha: 0,
                zoomable: false
            },
            categoryField: "riskCluster",
            categoryAxis: {
                hidePlus: this.hidePlus,
                autoGridCount: false,
                gridPosition: "start",
                tickPosition: "start",
                gridAlpha: 0,
                tickLength: 0,
                labelsEnabled: false
            },
            export: {
                enabled: false
            },
            listeners: [{
                event: "rendered",
                method: (e) => {
                    if (this.chart == undefined) this.chart = e.chart;
                    if (this.showRiskLevels) {
                        this.buildAxis(e.chart.categoryAxis.x);
                    }
                }
            },
            {
                event: "resized",
                method: (e) => {
                    if (this.showRiskLevels) {
                        this.buildAxis(e.chart.categoryAxis.x);
                    }
                }
            }]
        });
    }

    ngOnDestroy() {
        this.AmCharts.destroyChart(this.chart);
    }

    private setGraphs(): any[] {
        let graphs = [];

        if (this._chartData && this._chartData.length > 0) {
            if (this._chartData[0].hasOwnProperty('universe')) {
                graphs.push({
                    valueField: 'universe',
                    fillColors: '#A7A9AC',
                    fillAlphas: 1,
                    lineAlpha: 0,
                    type: 'column',
                    labelText: "[[value]]%",
                });
            }

            if (this._chartData[0].hasOwnProperty('subIndustry')) {
                graphs.push({
                    valueField: 'subIndustry',
                    fillColors: '#F0AB01',
                    fillAlphas: 1,
                    lineAlpha: 0,
                    type: 'column',
                    labelText: "[[value]]%",
                });
            }
        }

        return graphs;
    }

    private buildAxis(startLocation: number): void {
        if (this.riskLevels) {

            let labels = '';
            let scales = '';

            this.riskLevels.map((level) => {
                let width = 100 / this.riskLevels.length;
                labels += `<td class="text-center" width="${width}%">${level.name}</td>`;
                scales += `<td style="background-color:${level.color}; line-height:1em; font-size:8px;">&nbsp;</td>`;
            });

            let html = `
                <table style="margin-top: 5px; border-collapse: separate; border-spacing: 4px;" width="100%">
                    <tr>
                        ${scales}
                    </tr>
                    <tr>
                        ${labels}
                    </tr>
                </table>
            `;


            this.el.nativeElement.children.benchmarkChartAxis.innerHTML = html;
        }
    }

    private getMaxRating(): number {
        if (this._chartData && this._chartData.length > 0) {
            let maxUniverse = this._chartData[0].hasOwnProperty('universe') ? _.maxBy(this._chartData, 'universe').universe : 0;
            let maxSubindustry = this._chartData[0].hasOwnProperty('subIndustry') ? _.maxBy(this._chartData, 'subIndustry').subIndustry : 0;

            return Math.max(maxUniverse, maxSubindustry) + 10;
        }

        return undefined;
    }
}